/* eslint-disable prettier/prettier */
import { Controller, Get, Query, Res } from '@nestjs/common';
import { StudentService } from '../student/student.service';
import axios from 'axios';
/**
 * www.sss.com/wx/wxpay
 */
@Controller('wx')
export class WxpayController {
  constructor(private readonly studentService: StudentService) {}
  // 域名/wx/login
  @Get('login')
  async wxLogin(
    @Query('userId') userId: string,
    @Query('url') url: string,
    @Res() res,
  ): Promise<void> {
    const { WXPAY_APPID, REDIRECT_URI } = process.env;
    const STATE = `${userId}@${encodeURIComponent(url)}`;
    const redirectUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WXPAY_APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_base&state=${STATE}#wechat_redirect`;
    res.redirect(redirectUrl);
  }
  // 域名/wx/wxCode
  // 得到 code 然后用 code 去获取 access token 最终拿到 openid 
  @Get('wxCode')
  async wxCode(
    @Query('code') code: string,
    @Query('state') state: string,
    @Res() res,
  ) {
    const [userId, url] = state.split('@');
    const { WXPAY_APPID, WXPAY_SECRET } = process.env;
    const response = await axios.get(
      `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WXPAY_APPID}&secret=${WXPAY_SECRET}&code=${code}&grant_type=authorization_code`,
    );
    const { openid } = response.data;
    this.studentService.updateById(userId, {
      openid,
    });
    res.redirect(decodeURIComponent(url) + '?openid=' + openid);
  }
}
